<template>
    <div class="body1">
        <div class="no-print el-button-print">
            <el-button @click="addForm">添加清单页</el-button>
            <el-button @click="deleteForm">删除清单页</el-button>
            <el-button @click="exportPDF">导出为pdf</el-button>
        </div>

        <div class="body2" id="pdfDom" :class="{ 'pdf-export': isPdfExport }">
            <div class="title">
                <div class="biaotididian">{{ agencyName }}</div>
                <div class="biaoti">抽样（采样）通知书</div>
            </div>
            <div class="foreword1">
                <input v-model="form.a1" :resize="'none'" autosize maxlength="4" class="inputStyle1"
                    style="width: 80px;font-family: 仿宋;font-size: 5mm;text-align: center" type="textarea">
                <span>（</span>
                <reference-select style="width: 5mm;margin-bottom: 4px" v-model="form.referenceValue"
                    class="InvestigatorSelectReplace" />
                <span>）抽（采）通字[</span>
                <input v-model="form.a2" :resize="'none'" autosize maxlength="4" class="areaInputStyle"
                    style="width: 40px;font-family: 仿宋;font-size: 5mm;text-align: center" type="textarea"
                    oninput="this.value = this.value.replace(/[^a-zA-Z0-9_-]/g, '')">
                <span>]第</span>
                <input v-model="form.a3" :resize="'none'" autosize maxlength="5" class="areaInputStyle"
                    style="width: 50px;font-family: 仿宋;font-size: 5mm;text-align: center" type="textarea"
                    oninput="this.value = this.value.replace(/[^a-zA-Z0-9_-]/g, '')">
                <span>号</span>
            </div>
            <div class="tableStyle1">
                <div class="writ-height">
                    <div style="display: inline-block; position: relative;">
                        <privy-info-select v-model="form.unitName" v-model:isSelected="form.isUnit" return-fields="A(B)"
                            :rowConfig="unitNameConfig">
                        </privy-info-select>
                    </div>
                    <span>：</span>
                </div>
                <div style="height: 570px; line-height: 30px;">
                    <span>&nbsp;&nbsp;&nbsp;&nbsp;根据</span>
                    <input v-model="form.a5" :resize="'none'" autosize maxlength="28" class="inputStyle1"
                        style="width: calc(28 * 5mm);font-family: 仿宋;font-size: 5mm;text-align: center" type="textarea">
                    <span>，现决定对你单位的</span>
                    <input v-model="form.a6" :resize="'none'" autosize maxlength="23" class="inputStyle1"
                        style="width: calc(23 * 5mm);font-family: 仿宋;font-size: 5mm;text-align: center" type="textarea">
                    <span>等进行抽样（采样）。（附抽样（采样）物品清单）</span>

                    <div class="writ-height" style="margin-bottom: 1px">
                        <span>&nbsp;&nbsp;&nbsp;&nbsp;行政执法人员：</span>
                        <InvestigatorSelect class="InvestigatorSelectReplace"
                            style="height: 6mm; width: calc(6 * 5mm);margin-bottom: 4px;border-bottom: 1px solid black"
                            v-model="form.a12" :id-field="'a13'" @change="handleInvestigatorChange" />
                        <span>行政执法证号：</span>
                        <input v-model="form.a13" :resize="'none'" autosize class="inputStyle1" readonly
                            style="width: calc(10 * 5mm);font-family: 仿宋;font-size: 5mm;" type="textarea"
                            ref="inputRef6">
                    </div>
                    <div class="writ-height" style="margin-bottom: 1px">
                        <span>&nbsp;&nbsp;&nbsp;&nbsp;行政执法人员：</span>
                        <InvestigatorSelect class="InvestigatorSelectReplace"
                            style="height: 6mm; width: calc(6 * 5mm);margin-bottom: 4px;border-bottom: 1px solid black"
                            v-model="form.a14" :id-field="'a15'" @change="handleInvestigatorChange" />
                        <span>行政执法证号：</span>
                        <input v-model="form.a15" :resize="'none'" autosize class="inputStyle1" readonly
                            style="width: calc(10 * 5mm);font-family: 仿宋;font-size: 5mm;" type="textarea"
                            ref="inputRef6">
                    </div>
                </div>
                <div style="text-align: right; margin-top: 20px; margin-bottom: 50px;">
                    <div class="seal-container">
                        <span class="seal-name" v-html="sealName"></span>
                        <div class="delivery-agency-div" :class="{ 'official-seal-display': isDisplay }">
                            <editable-textarea :text="form.date1" param-type="YYYYMMDD1"
                                @send-to-parent="receiveFromChild" />
                            <img class="official-seal" src="../../assets/tupian.png" alt="Image">
                        </div>
                    </div>
                </div>
                <div style="line-height: 30px;">
                    <span>受送达人：</span><input v-model="form.a35" :resize="'none'" autosize maxlength="20"
                        class="inputStyle1" style="width: calc(20 * 5mm);font-family: 仿宋;font-size: 5mm;"
                        type="textarea">
                    <editable-textarea :text="form.date3" param-type="YYYYMMDD3" @send-to-parent="receiveFromChild" />
                    <br><span>送达方式与地址：</span><input v-model="form.a36" :resize="'none'" autosize maxlength="24"
                        class="inputStyle1" style="width: calc(24 * 5mm);font-family: 仿宋;font-size: 5mm;"
                        type="textarea">
                </div>
            </div>
            <!-- 清单 -->
            <div v-for="(item, index) in form.inventoryTable" :key="index" class="page-break">
                <div class="title">
                    <div class="biaotididian">抽样（采样）物品清单</div>
                </div>
                <table class="tableStyle">
                    <colgroup>
                        <col width="7%">
                        <col width="19%">
                        <col width="19%">
                        <col width="19%">
                        <col width="19%">
                        <col width="17%">
                    </colgroup>
                    <thead>
                        <tr>
                            <th style="height: 40px">编号</th>
                            <th>名称</th>
                            <th>数量/单位</th>
                            <th>规格</th>
                            <th>型号</th>
                            <th>批号</th>
                        </tr>
                    </thead>
                    <tbody>
                        <tr v-for="(item1, index1) in item" :key="index1">
                            <td height="80px">
                                <el-input v-model="item1.number" :resize="'none'" autosize maxlength="6"
                                    class="areaInputStyle" type="textarea" ref="inputRef6">
                                </el-input>
                            </td>
                            <td>
                                <el-input v-model="item1.name" :resize="'none'" autosize maxlength="18"
                                    class="areaInputStyle" type="textarea" ref="inputRef6">
                                </el-input>
                            </td>
                            <td>
                                <el-input v-model="item1.quantity" :resize="'none'" autosize maxlength="18"
                                    class="areaInputStyle" type="textarea" ref="inputRef6">
                                </el-input>
                            </td>
                            <td>
                                <el-input v-model="item1.specifications" :resize="'none'" autosize maxlength="18"
                                    class="areaInputStyle" type="textarea" ref="inputRef6">
                                </el-input>
                            </td>
                            <td>
                                <el-input v-model="item1.model" :resize="'none'" autosize maxlength="18"
                                    class="areaInputStyle" type="textarea" ref="inputRef6">
                                </el-input>
                            </td>
                            <td>
                                <el-input v-model="item1.remark" :resize="'none'" autosize maxlength="15"
                                    class="areaInputStyle" type="textarea" ref="inputRef6">
                                </el-input>
                            </td>
                        </tr>
                    </tbody>
                </table>
            </div>
        </div>
    </div>

</template>

<script>
import EditableTextarea from "@/views/template/EditableTextarea";
import { agencyName, sealName } from "../../utils/publicName.js"
import PrivyInfoSelect from "@/views/template/PrivyInfoSelect";
import LawsAndRegulationsSelect from "@/views/template/LawsAndRegulationsSelect";
import CrossRowInput from "@/views/template/CrossRowInput";
import ReferenceSelect from "@/views/template/ReferenceSelect";
import InvestigatorSelect from "@/views/template/InvestigatorSelect";

export default {
    components: {
        LawsAndRegulationsSelect,
        EditableTextarea,
        CrossRowInput,
        InvestigatorSelect,
        ReferenceSelect,
        PrivyInfoSelect,
    },

    data() {
        return {
            agencyName: agencyName,
            sealName: sealName,
            form: {
                inventoryTable: [[
                    { number: '', name: '', quantity: '', specifications: '', model: '', remark: '' },
                    { number: '', name: '', quantity: '', specifications: '', model: '', remark: '' },
                    { number: '', name: '', quantity: '', specifications: '', model: '', remark: '' },
                    { number: '', name: '', quantity: '', specifications: '', model: '', remark: '' },
                    { number: '', name: '', quantity: '', specifications: '', model: '', remark: '' },
                    { number: '', name: '', quantity: '', specifications: '', model: '', remark: '' },
                    { number: '', name: '', quantity: '', specifications: '', model: '', remark: '' },
                    { number: '', name: '', quantity: '', specifications: '', model: '', remark: '' },
                    { number: '', name: '', quantity: '', specifications: '', model: '', remark: '' },
                    { number: '', name: '', quantity: '', specifications: '', model: '', remark: '' },
                ]],
                isUnit: true,
            },
            status: '', //当前文书的状态
            isPdfExport: false, //控制打印样式
            isDisplay: true, //控制官方印章的显示
            unitNameConfig: {
                firstLine: { chars: 28 * 2 },
                middleLines: { count: 0, chars: 32 * 2 },
                lastLine: { chars: 0 * 2 }
            },
        }
    },

    created() {
        window.parent.getTemplateData((data, status) => {
            this.form = data;
            this.status = status;
        })
        window.postForm = () => {
            this.postForm();
        }
    },

    mounted() {
        window.parent.changeTemplateDow();
    },

    methods: {
        // 添加页
        addForm() {
            if (!Array.isArray(this.form.inventoryTable)) {
                this.form.inventoryTable = []; // 重置为数组
            }
            // 添加新页（包含10个空行）
            this.form.inventoryTable.push(Array(10).fill().map(() => ({
                number: '', name: '', quantity: '', specifications: '', model: '', remark: ''
            })));
        },
        // 删除页
        deleteForm() {
            // 确保至少保留一页
            if (this.form.inventoryTable.length > 1) {
                this.form.inventoryTable.pop();
            } else {
                this.$message.warning('至少保留一页');
            }
        },
        // 切换单位删除线
        switchUnitDelLine() {
            this.form.isUnit = !this.form.isUnit
        },
        // 导出为pdf
        exportPDF() {
            if (this.status !== '4') {
                this.isDisplay = false
            }
            this.savePDF()
                .then((blob) => {

                    const blobUrl = URL.createObjectURL(blob);

                    // 先预览
                    const previewWindow = window.open(blobUrl, '_blank');

                    // 自动下载
                    const fileName = `抽样（采样）通知书.pdf`;
                    const downloadLink = document.createElement('a');
                    downloadLink.href = blobUrl;
                    downloadLink.download = fileName;
                    document.body.appendChild(downloadLink);
                    downloadLink.click();
                    document.body.removeChild(downloadLink);

                    // 监听预览窗口关闭后释放内存
                    if (previewWindow) {
                        const timer = setInterval(() => {
                            if (previewWindow.closed) {
                                clearInterval(timer);
                                URL.revokeObjectURL(blobUrl);
                            }
                        }, 1000);
                    } else {
                        setTimeout(() => URL.revokeObjectURL(blobUrl), 10000); // 兜底释放
                    }
                })
                .catch(error => {
                    console.error('导出PDF出错:', error);
                    alert('导出失败，请重试或联系管理员');
                });
        },
        savePDF() {
            this.isPdfExport = true; // 激活PDF样式
            return new Promise((resolve, reject) => {
                this.$nextTick(() => {
                    import('html2pdf.js').then((module) => {
                        const html2pdf = module.default;

                        //获取所有需要替换的 el-input
                        const elInputs = document.querySelectorAll('.el-input__inner, .el-textarea__inner');

                        //存储原始元素和它们的父节点，方便后续恢复
                        const originalElements = [];

                        elInputs.forEach((input) => {
                            const div = document.createElement('div');
                            div.style.whiteSpace = 'pre-wrap'; // 保留换行
                            div.style.fontFamily = '仿宋';
                            div.style.fontSize = '5mm';
                            div.textContent = input.value; // 保留原内容（自动处理 \n 换行）
                            div.style.lineHeight = '1.3';

                            // 替换 el-input，并存储原始元素
                            originalElements.push({
                                parent: input.parentNode,
                                original: input,
                                replacement: div,
                            });
                            input.parentNode.replaceChild(div, input);
                        });

                        // 处理选择执法人的替换
                        const InvestigatorSelectSelects = document.querySelectorAll('.InvestigatorSelectReplace .el-input__inner, .InvestigatorSelectReplace .el-textarea__inner');
                        InvestigatorSelectSelects.forEach((input) => {
                            const div = document.createElement('div');
                            div.style.whiteSpace = 'pre-wrap'; // 保留换行
                            div.style.fontFamily = '仿宋';
                            div.style.fontSize = '5mm';
                            div.textContent = input.value; // 保留原内容（自动处理 \n 换行）
                            div.style.lineHeight = '1.3';

                            // 替换 el-input，并存储原始元素
                            originalElements.push({
                                parent: input.parentNode,
                                original: input,
                                replacement: div,
                            });
                            input.parentNode.replaceChild(div, input);
                        });

                        // 配置选项
                        const opt = {
                            margin: 0,
                            image: {
                                type: 'jpeg',
                                quality: 0.98
                            },
                            html2canvas: {
                                scale: 2,
                                logging: false,
                                useCORS: true
                            },
                            jsPDF: {
                                unit: 'mm',
                                format: 'a4',
                                orientation: 'portrait'
                            }
                        };

                        const element = document.getElementById('pdfDom');

                        // 生成PDF Blob对象
                        html2pdf()
                            .set(opt)
                            .from(element)
                            .toPdf()
                            .get('pdf')
                            .then((pdf) => {
                                const blob = pdf.output('blob');

                                resolve(blob); // 返回Blob对象
                            })
                            .catch((error) => {
                                reject(error);
                            })
                            .finally(() => {
                                this.isPdfExport = false; // 恢复原始样式
                                this.isDisplay = true;
                                // 恢复原始input
                                originalElements.forEach(({ parent, original, replacement }) => {
                                    parent.replaceChild(original, replacement);
                                });
                            });
                    }).catch((error) => {
                        reject(error);
                        this.isPdfExport = false;
                        this.isDisplay = true;
                        originalElements.forEach(({ parent, original, replacement }) => {
                            parent.replaceChild(original, replacement);
                        });
                    });
                });
            });
        },
        //父页面提交按钮将调用此方法，此方法将文书数据回传到父页面的请求方法中
        postForm() {
            this.savePDF()
                .then((blob) => {


                    // 创建FormData并添加文件
                    const formData = new FormData();
                    formData.append('file', blob, '抽样（采样）通知书.pdf');

                    window.parent.postTemplateDate(this.form, formData);
                })
                .catch(error => {
                    console.error('整个保存PDF出错:', error);
                });
        },
        //选择日期时间
        receiveFromChild(data, type) {
            const TypeMap = {
                'YYYYMMDD1': 'date1',
                'YYYYMMDD3': 'date3',
            };
            if (TypeMap[type]) {
                this.form[TypeMap[type]] = data;
            }
        },
        //选择执法人员
        handleInvestigatorChange({ identificationNumber, idField }) {
            if (idField && identificationNumber) {
                this.form[idField] = identificationNumber;
            }
        }
    }
}
</script>

<style scoped>
.official-seal {
    /* 公章隐藏，在打印时显示，具体打印会，print.css有显示样式。 */
    display: none;
    width: 4.2cm;
    height: 4.2cm;
    z-index: 20;

    /* 定位 */
    position: absolute;
    bottom: -20px;
    right: -10px;
}


:deep(.el-button-print .el-button) {
    display: inline-flex !important;
    visibility: visible !important;
    opacity: 1 !important;
    width: auto;
    min-width: 100px;
    height: auto;
    padding: 8px 15px;
    background: #fff !important;
    color: #000 !important;
    border: none;
}

:deep(.el-textarea__inner) {
    box-shadow: 0 0 0 0;
    color: black;
    padding: 0;
    font-family: "仿宋", serif;
    font-size: 5mm;
    overflow-y: hidden;
    line-height: 1.3;
    white-space: pre-wrap;
}

:deep(.el-textarea-hidden .el-textarea__inner) {
    box-shadow: 0 0 0 0;
    color: black;
    padding: 0;
    font-family: "仿宋", serif;
    font-size: 5mm;
    overflow-y: hidden !important;
    resize: none !important;
    height: auto !important;
}

:deep(.el-select .el-input__inner) {
    text-align: center;
    height: 5mm;
}

.input-container {
    width: 100%;
    display: flex;
    flex-wrap: wrap;
    align-items: flex-start;
}

.inputStyleNoLine {
    border: none;
    outline: none;
    padding: 0px;
}

.typeSpan {
    cursor: pointer;
    font-size: 5mm;
}
</style>
